
<template>
  <div class="app-container">

    <!--侧边部门数据-->
    <div class="head-container">
      <el-input v-model="deptName" clearable size="small" placeholder="输入部门名称搜索" :prefix-icon="Search"
        class="filter-item" @input="getDeptDatas" />
    </div>
    <!-- {{crud.dialogFormVisible}} -->
    <div class="head-container">
      <!-- {{crud.dialogFormVisible}} -->
      <operation />

      <el-row :gutter="15">
        <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="17" style="margin-bottom: 10px">

          <el-card class="box-card" shadow="never">


            <template #header>
              <div class="card-header">
                <span class="role-span">角色列表</span>
              </div>
            </template>






            <el-table :data="crud.data" style="width: 100%" v-loading="crud.loading"
              @selection-change="crud.selectionChangeHandler" @current-change="handleCurrentChange">
              <el-table-column type="selection" width="55" />
              <el-table-column prop="name" label="姓名" width="80" />
              <el-table-column prop="remark" label="备注" />

              <el-table-column prop="createdAt" label="创建时间" width="160" />
              <el-table-column prop="updatedAt" label="修改时间" width="160" />
              <el-table-column label="操作" width="180" align="center" fixed="right">
                <template #default="scope">
                  <udOperation :data="scope.row" />
                </template>
              </el-table-column>
            </el-table>
            <pagination />
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="7">
          <el-card class="box-card" shadow="never">







            <template #header>
              <div class="card-header">
                <el-tooltip class="item" effect="dark" content="选择指定角色分配菜单" placement="top">
                  <span class="role-span">菜单分配</span>
                </el-tooltip>
                <el-button size="small" @click="save" style="float: right; padding: 6px 9px" :disabled="isbutton"
                  type="primary">保存
                </el-button>
              </div>
            </template>




            <el-tree :data="menuDatas" ref="menu" show-checkbox node-key="id" highlight-current
              :default-checked-keys="menuIds" :props="defaultPropstree" />
          </el-card>
        </el-col>
      </el-row>
    </div>

    <eForm v-if="crud.dialogFormVisible" :deptlist="deptDatas" />
  </div>
</template>

<script setup lang="ts">
import crudROLE, { roleinfo, edit } from '/@/api/system/role';
import { getDepts } from '/@/api/system/dept';

import { ElMessage } from 'element-plus'
import { useRouter } from "vue-router";
import pagination from "/@/crud/Pagination.vue";
import udOperation from "/@/crud/udOperation.vue";
import { formatMenu2Tree } from '/@/utils/utils';
import eForm from "./model/form.vue";
import { list, add } from '/@/api/system/menu';
import { Search } from '@element-plus/icons-vue';
import { crud, CRUD } from '/@/crud/crud';
import operation from "/@/crud/operation.vue";
import { ref, reactive, watch, computed, getCurrentInstance } from "vue";
import { pick } from 'lodash-es';
CRUD({ title: '角色', url: 'admin/sys/role/page', type: 'get', crudMethod: { ...crudROLE } })
const deptName = ref("");
const menuIds = ref([]);
let roleobj = reactive({
  depts: [],
  menus: [],
  roleId: null,
  createdAt: null,
  id: null

})
const menu = ref()
const { proxy } = getCurrentInstance();
const deptDatas = ref([]);
const deptId = ref([]);
const isbutton = ref(true)

const menuDatas = ref([]);
const defaultProps = { children: 'children', label: 'name', isLeaf: 'leaf' }
const defaultPropstree = {
  children: 'children',
  label: 'label',
}


const getDeptDatas = () => {
  getDepts({}).then(res => {

    // formatDept2Tree(res)
    deptDatas.value = formatDeptTree(res.data)

  })
}
getDeptDatas()

const getmenuDatas = () => {
  list({}).then((res: any) => {

    menuDatas.value = formatMenu2Tree(JSON.parse(JSON.stringify(res.data)))



  })
}


getmenuDatas()

const handleCurrentChange = (val) => {
  if (!val) {
    return
  }
  menu.value!.setCheckedKeys([], false)

  roleinfo({ roleId: val.id }).then(res => {
    let list = res.data.menus.map(item => {
      return item.menuId
    })

    let dept = res.data.depts.map(item => {
      return item.departmentId
    })
    menuIds.value = list
    console.log(list, "list")
    isbutton.value = false,

      roleobj = val
    roleobj.depts = dept


  })




}

const save = () => {

  console.log(roleobj, "roleobj");

  roleobj.menus = menu.value!.getCheckedKeys(false)


  roleobj.roleId = roleobj.id
  let datas = pick(roleobj, 'roleId', 'remark', "name", "menus", "label", "depts")

  edit(datas).then((res: any) => {
    ElMessage.success('修改成功');

  })
}
const formatDeptTree = (
  depts: any,
  parentId: number | null = null,
  keyPath: (string | number)[] = [],
): any => {
  return depts
    .filter((item) => item.parentId === parentId)
    .map((item) => {
      const _keyPath = keyPath.concat(parentId || []);
      const arr = formatDeptTree(depts, item.id, _keyPath);
      return Object.assign(item, {
        keyPath: _keyPath,
        title: item.name,
        label: item.name,
        key: item.id,
        value: item.id,
        formData: item,
        children: arr.length ? arr : null,
      });
    });
};

const handleNodeClick = (data: any) => {
  console.log(data.id)
  crud.query.departmentIds = [data.id]
  crud.toQuery()
}
</script>
<style lang="scss" scoped>
.role-span {
  font-weight: bold;
}
</style>